package com.hupu.jrs.ui.main

import android.app.Fragment
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.net.Uri
import android.support.design.widget.NavigationView
import android.support.v4.view.GravityCompat
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.widget.Toolbar
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.afollestad.materialdialogs.MaterialDialog
import com.facebook.drawee.view.SimpleDraweeView
import com.hupu.jrs.Constants
import com.hupu.jrs.R
import com.hupu.jrs.injector.HasComponent
import com.hupu.jrs.ui.BaseActivity
import com.hupu.jrs.ui.account.AccountActivity
import com.hupu.jrs.ui.browser.BrowserActivity
import com.hupu.jrs.ui.login.LoginActivity
import com.hupu.jrs.ui.messagelist.MessageActivity
import com.hupu.jrs.ui.post.PostActivity
import com.hupu.jrs.ui.setting.SettingActivity
import com.hupu.jrs.ui.thread.recommend.RecommendThreadListFragment
import com.hupu.jrs.ui.userprofile.UserProfileActivity
import com.hupu.jrs.util.ResourceUtil
import com.hupu.jrs.util.SettingPrefUtil
import com.hupu.jrs.util.StatusBarUtil
import javax.inject.Inject
import butterknife.BindView
import butterknife.ButterKnife

/**
 * Created by sll on 2016/3/9.
 */
class MainActivity : BaseActivity(), View.OnClickListener, MainContract.View, HasComponent<MainComponent> {

    @BindView(R.id.navigationView)
    internal var navigationView: NavigationView? = null
    @BindView(R.id.drawerLayout)
    internal var drawerLayout: DrawerLayout? = null
    @BindView(R.id.toolbar)
    internal var toolbar: Toolbar? = null
    internal var ivTheme: ImageView
    internal var ivIcon: SimpleDraweeView
    internal var tvName: TextView

    @Inject
    internal var mPresenter: MainPresenter? = null

    override var component: MainComponent? = null
        private set(value: MainComponent?) {
            super.component = value
        }

    private var count = 0

    protected override val isApplyStatusBarTranslucency: Boolean
        get() = false

    protected override val isApplyStatusBarColor: Boolean
        get() = false

    override fun initContentView(): Int {
        return R.layout.activity_main
    }

    override fun initInjector() {
        component = DaggerMainComponent.builder()
                .applicationComponent(applicationComponent)
                .activityModule(activityModule).mainModule(MainModule(this))
                .build()
        component!!.inject(this)
    }

    override fun initUiAndListener() {
        ButterKnife.bind(this)
        setSupportActionBar(toolbar)
        supportActionBar!!.setHomeButtonEnabled(true) //设置返回键可用
        supportActionBar!!.setDisplayHomeAsUpEnabled(true)
        title = "帖子推荐"
        ivIcon = navigationView!!.getHeaderView(0).findViewById<View>(R.id.ivIcon) as SimpleDraweeView
        tvName = navigationView!!.getHeaderView(0).findViewById<View>(R.id.tvName) as TextView
        navigationView!!.getHeaderView(0).findViewById<View>(R.id.ivCover).setOnClickListener(this)
        navigationView!!.getHeaderView(0).findViewById<View>(R.id.llAccount).setOnClickListener(this)
        ivTheme = navigationView!!.getHeaderView(0).findViewById<View>(R.id.ivTheme) as ImageView
        ivTheme.setOnClickListener(this)
        ivTheme.setImageResource(if (SettingPrefUtil.getNightModel(this))
            R.drawable.ic_wb_sunny_white_24dp
        else
            R.drawable.ic_brightness_3_white_24dp)
        //创建返回键，并实现打开关/闭监听
        val mDrawerToggle = ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open, R.string.close)
        mDrawerToggle.syncState()
        drawerLayout!!.setDrawerListener(mDrawerToggle)
        StatusBarUtil.setColorForDrawerLayout(this, drawerLayout!!, ResourceUtil.getThemeColor(this), 0)
        setupDrawerContent()
        fragmentManager.beginTransaction()
                .replace(R.id.content,
                        RecommendThreadListFragment())
                .commit()
        mPresenter!!.attachView(this)
    }

    private fun setupDrawerContent() {
        navigationView!!.setNavigationItemSelectedListener { menuItem ->
            mPresenter!!.onNavigationClick(menuItem)
            true
        }
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.menu_main, menu)
        val menuItem = menu.findItem(R.id.action_notification)
        menuItem.icon = buildCounterDrawable(count, R.drawable.ic_menu_notification)
        return true
    }

    private fun buildCounterDrawable(count: Int, backgroundImageId: Int): Drawable {
        val inflater = LayoutInflater.from(this)
        val view = inflater.inflate(R.layout.notification_count_layout, null)
        view.setBackgroundResource(backgroundImageId)
        val tvCount = view.findViewById<View>(R.id.tvCount) as TextView
        if (count == 0) {
            tvCount.visibility = View.GONE
        } else {
            tvCount.visibility = View.VISIBLE
            tvCount.text = count.toString()
        }

        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
        view.layout(0, 0, view.measuredWidth, view.measuredHeight)

        view.isDrawingCacheEnabled = true
        view.drawingCacheQuality = View.DRAWING_CACHE_QUALITY_HIGH
        val bitmap = Bitmap.createBitmap(view.drawingCache)
        view.isDrawingCacheEnabled = false

        return BitmapDrawable(resources, bitmap)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> drawerLayout!!.openDrawer(GravityCompat.START)
            R.id.action_notification -> mPresenter!!.onNotificationClick()
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onBackPressed() {
        mPresenter!!.exist()
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.ivCover -> mPresenter!!.onCoverClick()
            R.id.llAccount -> mPresenter!!.showAccountMenu()
            R.id.ivTheme -> mPresenter!!.onNightModelClick()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mPresenter!!.detachView()
    }

    fun renderUserInfo(user: User?) {
        if (user != null) {
            if (!TextUtils.isEmpty(user.icon)) {
                ivIcon.setImageURI(Uri.parse(user.icon))
            }
            tvName.text = user.userName
        } else {
            ivIcon.setImageURI("")
            tvName.text = null
        }
    }

    fun renderAccountList(users: List<User>, items: Array<String>) {
        MaterialDialog.Builder(this).items(*items).itemsCallback { dialog, itemView, which, text -> mPresenter!!.onAccountItemClick(which, users, items) }.show()
    }

    override fun renderNotification(count: Int) {
        this.count = count
        invalidateOptionsMenu()
    }

    override fun closeDrawers() {
        drawerLayout!!.closeDrawers()
    }

    override fun showFragment(fragment: Fragment) {
        fragmentManager.beginTransaction().replace(R.id.content, fragment).commit()
    }

    override fun showMessageUi() {
        MessageActivity.startActivity(this)
    }

    override fun showUserProfileUi(uid: String) {
        UserProfileActivity.startActivity(this, uid)
    }

    override fun showLoginUi() {
        LoginActivity.startActivity(this)
    }

    override fun showAccountUi() {
        AccountActivity.startActivity(this)
    }

    override fun showSettingUi() {
        SettingActivity.startActivity(this)
    }

    override fun showFeedBackUi() {
        PostActivity.startActivity(this@MainActivity, Constants.TYPE_FEEDBACK, "", "2869008", "",
                "TLint For Android")
    }

    override fun showAboutUi() {
        BrowserActivity.startActivity(this, "http://www.pursll.com/TLint")
    }

    companion object {

        fun startActivity(mContext: Context) {
            val intent = Intent(mContext, MainActivity::class.java)
            mContext.startActivity(intent)
        }
    }
}
